//
//      Copyright Timothy Evans 2014 2015    timothy.evans@gsecraif.org
//
//      This file is part of gsecraif.
//
//      gsecraif is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 3 of the License, or
//      (at your option) any later version.
//
//      See gsecraif.cpp
//
// =====================================================================
//
//! Calculate the parity from a vector of (length) bytes.
//
// =====================================================================
// 
// Compile with g++
#include "parity.h"

using namespace std;
unsigned char parity(vector<unsigned char> bytes)
{
unsigned char par;	// byte holding parity value for array of bytes
vector<unsigned char>::iterator byte;
// gcc version 4.7.2 (Debian 4.7.2-5) does not seem to work
// with auto for iterators

if (bytes.begin() == bytes.end() ) {
    // It is not possible to properly calculate parity with less than two bytes,
    // however for one byte, that byte can be returned, as the parity of itself
    // (implicitly XOR'ed with null or zero)
    // But for no bytes something has gone wrong and so just return zero
    return 0;
    }
par=bytes[0];  // temp assignment to get going

for (byte = bytes.begin() + 1; byte != bytes.end(); ++byte) {
    par = par ^ *byte;
    }    
return par;
}
/*

Eg of parity calculation and parity triangles:

0
|\
| \
1--p1
  /|
 / |
2--p2
  /|
 / |
3--p3
  /|
 / |
4--p4
  /|
 / |
5--p5
  /|
 / |
6--p6

p6 is end result

*/
